// miniprogram/pages/home/home.js
const db = wx.cloud.database()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    location: {},
    markers: [],
    show: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.initData()
  },

  async initData(){
    const _ = db.command
    let location = await wx.getLocation({ type: "gcj02" })
    this.setData({ location })
    app.globalData.location = location
    wx.setStorageSync('location', location)
    let { data } = await db.collection('article').where({
      location: _.geoNear({
        geometry: db.Geo.Point(location.longitude, location.latitude),
        minDistance: 0,
        maxDistance: 100,
      })
    }).get()
    console.log(data)
    let markers = []
    for(let ele in data){
      let marker = {
        id: parseInt(ele),
        content: data[ele].content,
        ...data[ele].location,
        images: data[ele].fileList,
        userInfo: data[ele].userInfo,
        createDate: data[ele].createDate,
        customCallout: {
          display: 'ALWAYS',
          anchorX: 0,
          anchorY:0
        }
      }
      markers.push(marker)
    }
    
    this.setData({markers })
  },

  callouttap(e){
    console.log(e)
    let id = e.detail.markerId
    this.setData({
      curRecord: this.data.markers[id],
      show: true
    })
  },
  onClose(){
    this.setData({show:false})
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  onAddShare(){
    wx.navigateTo({
      url: '../../pages/add/add',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})